﻿#include "mbase_object.h"
#include <QGraphicsView>
#include <QStyleOptionGraphicsItem>
#include <QDebug>
#include <QComboBox>
#include <QStringList>
#include <QVBoxLayout>
#include <QSizePolicy>
#include <mbasescene.h>
#include <math.h>
#include <QApplication>


//静态成员变量的类外初始化
//QStringList MBaseObject::carNumbers = {NetConnection::getLocalCarnumber()};
QColor MBaseObject::gBorderColor = QColor(14, 14, 255);

MBaseObject::MBaseObject(QGraphicsObject *parent)
    : QGraphicsObject(parent)
    , bSelected(false)
    , mPenWidthF(1)
{
    this->setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton);
    this->setAcceptHoverEvents(true);
    this->setFlags(  QGraphicsItem::ItemIsMovable
                     | QGraphicsItem::ItemIsFocusable);//焦点项，能够允许图形项成为焦点，从而响应键盘事件
    this->setFlag(QGraphicsItem::ItemIsSelectable);
    this->setFlag(QGraphicsItem::ItemSendsGeometryChanges);

}

MBaseObject::~MBaseObject()
{

}

//这里写了被选中函数，因此能够被继承
void MBaseObject::drawSelectedRect(QPainter *painter)
{
    if(MBaseScene::isbedrawLine)
        return;
    QRectF rect = this->boundingRect();
    painter->setPen(QPen(MBaseObject::gBorderColor, 1 , Qt::DashLine));//采用虚线绘制相应的选中框
    painter->setBrush(Qt::NoBrush);
    //虚线框的绘制，分别向左上角和右下角扩张一个单位
    painter->drawRect(rect.adjusted(-1, -1, 1, 1));
}


/*各种鼠标动作的响应函数*/
void MBaseObject::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    bSelected = true;
    QGraphicsView *view = this->scene()->views()[0]; /* 获取该图元所属的 view,因为这里只有一个view, 故只取第0个 */
    view->viewport()->setCursor(Qt::SizeAllCursor); /* 设置鼠标为手型 ，可以被拖动*/
    offset = this->pos() - computeTopLeftGridPoint(this->pos());
    return QGraphicsObject::mousePressEvent(event);
}

void MBaseObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    return QGraphicsObject::mouseMoveEvent(event);
}


QPointF MBaseObject::computeTopLeftGridPoint(const QPointF &pointP)
{
    int gridSize = 10;
    qreal xV = floor(pointP.x()/gridSize)*gridSize;
    qreal yV = floor(pointP.y()/gridSize)*gridSize;
    return QPointF(xV, yV);
}


QVariant MBaseObject::itemChange(GraphicsItemChange change , const QVariant &value)
{
    if (change == ItemPositionChange && scene()) {
            QPointF newPos = value.toPointF();
            if(QApplication::mouseButtons() == Qt::LeftButton){
                    QPointF closestPoint = computeTopLeftGridPoint(newPos);
                    return  closestPoint+=offset;
                    /*每次移动都返回当前点击位置与最近的左上角网格点的偏移量*/
                }
            else
                return newPos;
        }
        else
    return QGraphicsItem::itemChange(change, value);
}


void MBaseObject::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
    Q_UNUSED(event);
    if(!bSelected) return;
    QGraphicsView *view = this->scene()->views()[0]; /*  */
    view->viewport()->setCursor(Qt::ArrowCursor); /* 设置鼠标为箭头 */

}

////相应的键值选择，能够实现对图元的旋转删除
//void MBaseObject::keyReleaseEvent(QKeyEvent *event)
//{
//    if(!this->isSelected()) return;
//    //旋转角度
//    qreal offset;
//    if(event->key() == Qt::Key_Space)
//    {
//        //旋转90度，再将新的角度赋值给对象
//        offset = this->rotation() + 90;
//        this->setRotation(offset);
//    }
//    else if(event->key() == Qt::Key_Delete)
//    {
//        qDebug() << "2";
//        this->scene()->removeItem(this);
//    }
//}


//双击改变属性，是否应该在这里写
void MBaseObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    //输出位置的函数
//    qDebug() << event->scenePos();
    if(MBaseScene::isbedrawLine)
        return;

    QDialog *dialog = new QDialog;
    dialog->setWindowTitle("Set The Car");
    dialog->setWindowIcon(QIcon(":/image/SmallWIn.png"));
    //真的无语，搞去个问号搞这么麻烦
    dialog->setWindowFlags(dialog->windowFlags()&~Qt::WindowContextHelpButtonHint);
    //尺寸设置报错
    //    dialog->setSizePolicy(QSizePolicy::Ignored);
    dialog->resize(200,100);

    QComboBox *comboBox = new QComboBox();

    //这里通过后期的扫描来确定具体的车牌号
//    QStringList carNumbers = {"FS111" , "GD111" ,"CN111","CN222", "GD222","FS222"};    

    //将元素添加到可选框中
    comboBox->addItems(*mcarNumbers);
    //在dialog上面创建了垂直布局
    QVBoxLayout* layout = new QVBoxLayout(dialog);
    //将combo设置上去
    layout->addWidget(comboBox);

    // 显示对话框并等待用户选择
    if (dialog->exec() == QDialog::Rejected) {
        // 获取用户选择的 CarNumberItem,这里进行了剪切
        QString selectedCar = comboBox->currentText();
        QString selectedCarNumber = selectedCar.left(5);
        QString selectedCarIPstr = selectedCar.mid( 6, selectedCar.length() - 7);
        //这个坐标变换前面也遇到过,这里将图形旋转后会报错
        //        QGraphicsItem *item = nullptr;
        //        item = scene()->itemAt(this->scenePos(),transform());
        //关于这里的itemAT选择，为什么直接就能选择到了大图元，也很迷
        foreach (QGraphicsItem *item, this->scene()->selectedItems())
        {
            if(item == nullptr){
                qDebug() << "the item is empty!";
                return;
            }
            MBaseObject  *theitem = qgraphicsitem_cast<MBaseObject*>(item);
            theitem->CarNumberItem->setPlainText(selectedCarNumber);
            theitem->carIPstr = selectedCarIPstr;
            qDebug() << "Dialog accepted";
            qDebug() << "Selected Car Number Item: " << selectedCarNumber;
            qDebug() << selectedCarIPstr;
        }
    }
    return QGraphicsObject::mouseDoubleClickEvent(event);
}
